package com.qf.flash.ui.home;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.Constants;
import com.qf.flash.http.response.AreaMsgBean;
import com.qf.flash.model.GameGroupBean;
import com.qf.flash.model.HomeTopBean;
import com.qf.flash.model.RegionBean;
import com.qf.flash.mvp.contract.GameContract;
import com.qf.flash.mvp.contract.HomeContract;
import com.qf.flash.mvp.contract.LocationContract;
import com.qf.flash.mvp.presenter.BannerPresenter;
import com.qf.flash.mvp.presenter.GameWaitePresenter;
import com.qf.flash.mvp.presenter.LocationPresenterImpl;
import com.qf.flash.ui.home.adapter.GameGroupItem;
import com.qf.flash.ui.home.adapter.HomeTopItem;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.LazyBaseFragment;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.permission.PermissionManager;
import com.qf.flashlib.sharedpreferences.SavePermanentSharePrefs;
import com.qf.flashlib.sharedpreferences.SharePrefConstants;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建日期：2020/2/22 on 20:27
 * 描述:
 * 作者:戴旭东
 */
public class HomeFragment extends LazyBaseFragment implements LocationContract.View, HomeContract.View, GameContract.View {
    private static final String TAG = "tag";
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;

    private RVAdapter<Object> mAdapter;
    private LocationPresenterImpl mLocatePresenter;
    private BannerPresenter bannerPresenter;
    private GameWaitePresenter gameWaitePresenter;
    private HomeTopBean homeTopBean;
    private List<GameGroupBean> gameList;

    @Override
    protected int setContentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        initRefresh();
        initRecyclerView();
    }

    private void initRefresh() {
        mRefresh.setEnableLoadMore(false);
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                bannerPresenter.getBannerPlayType();
                String areaId = SavePermanentSharePrefs.getInstance().getDataString(SharePrefConstants.AREA_ID);
                getGameData(areaId);
            }
        });
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    private void initRecyclerView() {
        mAdapter = new RVAdapter<>(new HomeTopItem(getActivity()), new GameGroupItem());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new RVAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_more:
                        GroupHallActivity.start(getActivity(), 0);
                        break;
                    case R.id.cv_group:
                        Object data = mAdapter.getData(position);
                        if (data instanceof GameGroupBean) {
                            GameGroupBean bean = (GameGroupBean) data;
                            GroupDetailActivity.start(getActivity(), bean.getId(), bean.getPlayId());
//                            ChoseBusinessActivity.start(getActivity(), bean.getPlayId(), bean.getId());
                        }

                        break;
                }
            }
        });
    }

    @Override
    protected void initInject() {
        super.initInject();
        mLocatePresenter = new LocationPresenterImpl(getActivity());
        bannerPresenter = new BannerPresenter();
        gameWaitePresenter = new GameWaitePresenter();
        initPresenters(mLocatePresenter, bannerPresenter, gameWaitePresenter);

    }

    @Override
    protected void lazyLoad() {
        requestPermission();
        bannerPresenter.getBannerPlayType();
    }


    private void requestPermission() {
        new PermissionManager(this)
                .addPermission(Constants.LOCATE_PERMISSION)
                .addListener(new PermissionManager.OnPermissionListener() {
                    @Override
                    public void onSuccess(List<String> permissions) {
                        mLocatePresenter.startOncetLocation();
                    }

                    @Override
                    public void onFailed(List<String> permissions) {
                        FlashLib.showToast("权限拒绝");
                    }
                });
    }


    @OnClick({R.id.tv_location, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_location:
                ChangeRegionActivity.start(getActivity(), tvLocation.getText().toString(), 0);
                break;
            case R.id.tv_search:
                HomeSearchActivity.start(getActivity());
                break;
        }
    }

    @Override
    @Subscribe
    public void onLocationSuccess(AMapLocation location) {
        tvLocation.setText(location.getDistrict());
        bannerPresenter.getAreaId(location.getAdCode());
    }

    @Override
    public void onLocationFailed(String msg) {
        Log.e(TAG, "onLocationFailed: " + msg);
        FlashLib.showToast("定位失败");
    }

    @Subscribe
    public void onRegionChangeEvent(RegionBean regionBean) {
        tvLocation.setText(regionBean.getName());
        SavePermanentSharePrefs.getInstance().setData(SharePrefConstants.AREA_ID, regionBean.getId());
        SavePermanentSharePrefs.getInstance().setData(SharePrefConstants.CITY_ID, regionBean.getPid());
        getGameData(regionBean.getId());
    }


    @Override
    public void setBannerPlayTypeData(HomeTopBean homeTopBean) {
        ViewUtil.setRefreshComplete(mRefresh, true);
        List<Object> datas = mAdapter.getDatas();
        if (homeTopBean != null)
            datas.remove(this.homeTopBean);
        this.homeTopBean = homeTopBean;
        datas.add(0, homeTopBean);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void setAreaId(AreaMsgBean area) {
        if (area == null) {
            return;
        }
        SavePermanentSharePrefs.getInstance().setData(SharePrefConstants.CITY_ID, area.getPid());
        getGameData(area.getId());
    }

    private void getGameData(String areaId) {
        SavePermanentSharePrefs.getInstance().setData(SharePrefConstants.AREA_ID, areaId);
        gameWaitePresenter.getGameList(UserMgr.getInstance().getLoginUser().getUid(), areaId, 1);
    }

    @Override
    public void setGameList(List<GameGroupBean> data, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, true);
        List<Object> datas = mAdapter.getDatas();
        if (gameList != null)
            datas.removeAll(gameList);
        this.gameList = data;
        datas.addAll(data);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, true);
    }
}
